import React, { useEffect, useState } from 'react'
import { Button, DatePicker, Popconfirm, Table } from 'antd'
import dayjs from 'dayjs'
import Edit from './edit'
import Add from './add'

function Index(props) {
  const [tableData, setTableData] = useState([])
  const columns = [
    { title: '项目', dataIndex: 'projectName', key: 'projectName' },
    { title: '工时', dataIndex: 'time', key: 'time' },
    { title: '工作内容', dataIndex: 'content', key: 'content' },
    {
      title: '操作',
      key: 'action',
      width: 170,
      render: (text, record) => (
        <div>
          <Button type={'link'} onClick={() => edit(record)}>编辑</Button>
          <Popconfirm
            title="确认删除吗?"
            onConfirm={() => {
              remove(record)
            }}
            okText="Yes"
            cancelText="No"
          ><Button type={'link'} danger>删除</Button></Popconfirm>
        </div>
      )
    }
  ]
  const [date, setDate] = useState(dayjs())

  function dateChange(date) {
    setDate(date)
  }

  async function getData() {
    let res = await window.electron.ipcRenderer.invoke('today-list', { date: dayjs(date).format('YYYY-MM-DD') })
    setTableData(res)
  }

  useEffect(() => {
    getData()
  }, [])

  useEffect(() => {
    getData()
  }, [date])

  //添加
  const [addVisible, setAddVisible] = useState(false)

  async function saveAdd(data) {
    let param = data.map((item) => {
      delete item.key
      item.date = dayjs(date).format('YYYY-MM-DD')
      return item
    })
    await window.electron.ipcRenderer.invoke('today-add', { list: param })
    setAddVisible(false)
    await getData()
  }


  //编辑
  const [editVisible, setEditVisible] = useState(false)
  const [current, setCurrent] = useState(null)

  function edit(record) {
    setCurrent(record)
    setEditVisible(true)
  }

  async function saveEdit(data) {
    await window.electron.ipcRenderer.invoke('today-edit', { ...data, date: dayjs(date).format('YYYY-MM-DD') })
    setEditVisible(false)
    await getData()
  }

  //删除
  async function remove(record) {
    await window.electron.ipcRenderer.invoke('today-delete', record)
    await getData()
  }

  return (
    <div>
      <div className={'mb-4 flex justify-end'}>
        <DatePicker defaultValue={date} onChange={dateChange}></DatePicker>
        <Button type={'primary'} className={'ml-4'} onClick={() => setAddVisible(true)}>添加</Button>
      </div>
      <Table columns={columns} dataSource={tableData} bordered pagination={{ position: ['none'] }} rowKey={'id'} />
      <Edit visible={editVisible} onCancel={() => setEditVisible(false)} current={current} onSave={saveEdit}></Edit>
      <Add visible={addVisible} onCancel={() => setAddVisible(false)} onSave={saveAdd}></Add>
    </div>
  )
}

export default Index
